#include <p18F4520.h>
#include "ieee_robot.h"
#include "motor.h"



/*
 *Function Name:init_ccp1
 *
 *Parameters: none
 *
 *Description: This functions initializes the CCP1
 * module to run as standard pwm single output. It
 * follows the sets in 16.4.9 section of
 * PIC18F4520 datasheet
 *Returns: nothing
 *
 */
void init_ccp1(void) {
    //set RC2/P1A as input by setting
    //TRISC.RC2 = 1
    //and set RD5/P1B as input as 
    //said in 16.4.9 of datasheet
    TRISC = set_bit(TRISC,PWM_PN);
    TRISD = set_bit(TRISD,5);
    

    //set the PR2 setting required for
    //20 kHz pwm setting
    PR2 = (unsigned char)FREQ_SETTING;
    
    //configure CCP1 for single output PWM
    //P1A active high
    CCP1CON = 0x0C;
    
    //set TMR2 prescaler to 1:1 (divide by 1)
    //by clearing T2CON<1:0>
    T2CON = (T2CON & (~(0x03)));
}

/*
 *Function Name:start_ccp1
 *Parameters: none
 *Prerequisites: call to init_ccp1() has taken place 
 *Description: this functions
 *
 *Returns:
 *
 */

void start_ccp1(void) {
    unsigned char x = 0;
    //clear TMR2IF flag
    PIR1 = clear_bit(PIR1,1);
    
    //set TMR2ON bit
    T2CON = set_bit(T2CON,2);
     
    //wait until TMR2IF flag is set
    while (test_bit(PIR1,1) == 0);
    

    //set PWM pin to output
    TRISC = clear_bit(TRISC,PWM_PN);

    //this operation is specified
    //in 16.4.9
    ECCP1AS = clear_bit(ECCP1AS,7);
}

void set_duty_ccp1 (unsigned char duty) {
    //assume we only have 8 bit
    //pwm duty cycle resolution
    //unless this changes
     
    //set lower 2 lsbs in CCP1CON<5:4>
    CCP1CON = CCP1CON | ((duty & (0x03)) << 4);

    //set msignificant 6 bits
    CCPR1L = (duty >> 2);
}
